package org.xiaom.butler.dao.base;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
public abstract class BaseDao<T, ID extends Serializable> extends
		HibernateDaoSupport implements IBaseDao<T, ID>{
	Class clazz=(Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];;
 
	public T get(ID id) {
		return getHibernateTemplate().get(getEntityClass(), id);
	}
	public T save(T bean){
		getHibernateTemplate().save(getHibernateTemplate());
		return bean;
	}
	public T update(T bean){
		getHibernateTemplate().update(bean);	
		return bean;
	}
	public void delete(ID id){
		getHibernateTemplate().delete(get(id)); 
	}
	public List<T> getList(String hql){
		return getHibernateTemplate().find(hql);
	}
	public List<T> getPage(String hql,int page,int size){
		return null;
	}
	public void execute(final String cmdString,final String[] params){
		getHibernateTemplate().execute(new HibernateCallback<T>() {
			@Override
			public T doInHibernate(Session session) throws HibernateException,
					SQLException {
				Query q=session.createQuery(cmdString);
				for(int i=0;i<params.length;i++){
					q.setParameter(i,params[i]);
				}
				q.executeUpdate();
				return null;
			}
		});
	} 
	public Class<T> getEntityClass(){
		return clazz;
	}
	@Resource(name = "hibernateTemplate")
	public void setSuperHibernateTemplate(HibernateTemplate hibernateTemplate) {
		super.setHibernateTemplate(hibernateTemplate);
	}
	
}
